package com.lzs.adx.web.modules.adx.controller;

import cn.hutool.core.collection.CollectionUtil;
import com.alibaba.excel.EasyExcel;
import com.alibaba.excel.ExcelReader;
import com.alibaba.excel.read.metadata.ReadSheet;
import com.lzs.adx.commmon.constant.Constant;
import com.lzs.adx.commmon.page.PageData;
import com.lzs.adx.commmon.utils.Result;
import com.lzs.adx.commmon.validator.AssertUtils;
import com.lzs.adx.commmon.validator.ValidatorUtils;
import com.lzs.adx.commmon.validator.group.AddGroup;
import com.lzs.adx.commmon.validator.group.DefaultGroup;
import com.lzs.adx.commmon.validator.group.UpdateGroup;
import com.lzs.adx.web.commmon.annotation.LogOperation;
import com.lzs.adx.web.commmon.support.CustomExcelListener;
import com.lzs.adx.web.commmon.support.ReportExcelListener;
import com.lzs.adx.web.commmon.utils.ExcelUtils;
import com.lzs.adx.web.modules.adx.dto.AccountDTO;
import com.lzs.adx.web.modules.adx.dto.ReportExcelDTO;
import com.lzs.adx.web.modules.adx.dto.TotalStatisticsDTO;
import com.lzs.adx.web.modules.adx.excel.TotalStatisticsExcel;
import com.lzs.adx.web.modules.adx.service.TotalStatisticsService;
import com.lzs.adx.web.modules.security.user.SecurityUser;
import com.lzs.adx.web.modules.security.user.UserDetail;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.ResourceUtils;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import springfox.documentation.annotations.ApiIgnore;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.nio.charset.StandardCharsets;
import java.util.Date;
import java.util.List;
import java.util.Map;


/**
 * 汇总统计表
 *
 * @author wangzhijun 825400558@qq.com
 * @since 1.0.0 2024-09-10
 */
@RestController
@RequestMapping("adx/totalstatistics")
@Api(tags="汇总统计表")
public class TotalStatisticsController {
    @Autowired
    private TotalStatisticsService totalStatisticsService;

    @GetMapping("page")
    @ApiOperation("分页")
    @ApiImplicitParams({
        @ApiImplicitParam(name = Constant.PAGE, value = "当前页码，从1开始", paramType = "query", required = true, dataType="int") ,
        @ApiImplicitParam(name = Constant.LIMIT, value = "每页显示记录数", paramType = "query",required = true, dataType="int") ,
        @ApiImplicitParam(name = Constant.ORDER_FIELD, value = "排序字段", paramType = "query", dataType="String") ,
        @ApiImplicitParam(name = Constant.ORDER, value = "排序方式，可选值(asc、desc)", paramType = "query", dataType="String")
    })
    @RequiresPermissions("adx:totalstatistics:page")
    public Result<PageData<TotalStatisticsDTO>> page(@ApiIgnore @RequestParam Map<String, Object> params){
        PageData<TotalStatisticsDTO> page = totalStatisticsService.page(params);

        return new Result<PageData<TotalStatisticsDTO>>().ok(page);
    }

    @GetMapping("{id}")
    @ApiOperation("信息")
    @RequiresPermissions("adx:totalstatistics:info")
    public Result<TotalStatisticsDTO> get(@PathVariable("id") Long id){
        TotalStatisticsDTO data = totalStatisticsService.get(id);

        return new Result<TotalStatisticsDTO>().ok(data);
    }

    @PostMapping
    @ApiOperation("保存")
    @LogOperation("保存")
    @RequiresPermissions("adx:totalstatistics:save")
    public Result save(@RequestBody TotalStatisticsDTO dto){
        //效验数据
        ValidatorUtils.validateEntity(dto, AddGroup.class, DefaultGroup.class);
        UserDetail user = SecurityUser.getUser();
        dto.setUserId(user.getId());
        totalStatisticsService.save(dto);

        return new Result();
    }

    @PutMapping
    @ApiOperation("修改")
    @LogOperation("修改")
    @RequiresPermissions("adx:totalstatistics:update")
    public Result update(@RequestBody TotalStatisticsDTO dto){
        UserDetail user = SecurityUser.getUser();
        dto.setUserId(user.getId());
        //效验数据
        ValidatorUtils.validateEntity(dto, UpdateGroup.class, DefaultGroup.class);

        totalStatisticsService.update(dto);

        return new Result();
    }

    /**
     * 复制一个一模一样的账号
     * @param id
     * @return
     */
    @GetMapping("copy")
    public Result copy(Long id){

        TotalStatisticsDTO totalStatisticsDTO = totalStatisticsService.get(id);
        totalStatisticsDTO.setId(null);
        totalStatisticsDTO.setCreateTime(new Date());
        totalStatisticsDTO.setUpdateTime(new Date());
        totalStatisticsService.save(totalStatisticsDTO);
        return new Result().ok();
    }


    @DeleteMapping
    @ApiOperation("删除")
    @LogOperation("删除")
    @RequiresPermissions("adx:totalstatistics:delete")
    public Result delete(@RequestBody Long[] ids){
        //效验数据
        AssertUtils.isArrayEmpty(ids, "id");

        totalStatisticsService.delete(ids);

        return new Result();
    }

    @GetMapping("export")
    @ApiOperation("导出")
    @LogOperation("导出")
    @RequiresPermissions("adx:totalstatistics:export")
    public void export(@ApiIgnore @RequestParam Map<String, Object> params, HttpServletResponse response) throws Exception {
        List<TotalStatisticsDTO> list = totalStatisticsService.list(params);

        ExcelUtils.exportExcelToTarget(response, null, list, TotalStatisticsExcel.class);
    }

    @GetMapping("download")
    public void download(HttpServletResponse response) throws IOException {
//        File file = new File(ResourceUtils.getFile(ResourceUtils.CLASSPATH_URL_PREFIX),"data/totalStatistics.xlsx");
        File file = new File("/data/ap02/file/totalStatistics.xlsx");
        if(file.exists()) {
            response.setContentType("application/force-download");
            response.addHeader("Content-Disposition", "attachment;fileName="+ new String("汇总报表模板".getBytes(), StandardCharsets.ISO_8859_1)+".xlsx");
            FileInputStream input = new FileInputStream(file);
            ServletOutputStream out = response.getOutputStream();
            int real;
            byte[] bytes = new byte[1024];
            while ((real=input.read(bytes))!=-1) {
                out.write(bytes, 0, real);
            }
            input.close();
            out.close();
        }
    }


    /**
     * 导入数据
     */
    @PostMapping("/import")
    public Result importData(MultipartFile file) {
        try {
            //获取文件的输入流
            InputStream inputStream = file.getInputStream();
            CustomExcelListener listener = new CustomExcelListener();
            ExcelReader excelReader = EasyExcel.read(inputStream).build();
            List<ReadSheet> readSheets = excelReader.excelExecutor().sheetList();

            for (ReadSheet readSheet : readSheets) {
                String sheetName = readSheet.getSheetName();
                if(StringUtils.startsWithIgnoreCase(sheetName,"000")) {
                    continue;
                }
                    excelReader.read(
                            EasyExcel.readSheet(readSheet.getSheetNo())
                                    .registerReadListener(listener)
                                    .headRowNumber(1)
                                    .build()
                    );
                }
            excelReader.finish();
            List<TotalStatisticsDTO> list = listener.getDataList();

            if(CollectionUtil.isNotEmpty(list)){
                for (TotalStatisticsDTO totalStatisticsDTO : list) {
                    totalStatisticsDTO.setUserId(SecurityUser.getUser().getId());
                    totalStatisticsService.generateData(totalStatisticsDTO);
                }
            }
            return new Result();
        } catch (IOException exception) {
            throw new RuntimeException(exception);
        }
    }

}